package cn.dansj.configure;

import cn.dansj.common.jdbc.hibernate.model.nameing.JpaImplicitNamingStrategy;
import cn.dansj.common.context.GetEnvironment;
import com.alibaba.druid.pool.DruidDataSource;
import com.xxl.job.configure.XxlJobDataSourceConfigure;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.*;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.*;

@Configuration
@EnableJpaRepositories(basePackages = {"cn.dansj.repository", XxlJobDataSourceConfigure.XxlJobRepository})
@EnableTransactionManagement
public class DataSourceConfigure {
    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, DruidDataSource dataSource) {
        return builder.dataSource(dataSource).properties(buildProperties()).packages("cn.dansj.entity", XxlJobDataSourceConfigure.XxlJobEntity).build();
    }

    @Bean
    @Primary
    public PlatformTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean entityManagerFactory) {
        return new JpaTransactionManager(Objects.requireNonNull(entityManagerFactory.getObject()));
    }

    // 公共jpa设置
    private final String ddl = GetEnvironment.get("spring.jpa.hibernate.ddl-auto", "none");
    private final String showSql = GetEnvironment.get("spring.jpa.show-sql", "false");

    private Map<String, Object> buildProperties() {
        Map<String, Object> properties = new HashMap<>();
        properties.put("hibernate.implicit_naming_strategy", JpaImplicitNamingStrategy.class.getName());
        properties.put("hibernate.hbm2ddl.auto", ddl);
        properties.put("hibernate.show_sql", showSql);
        return properties;
    }
}
